/*-
 * ReadPhonebookEntries.java
 *
 * $LastChangedBy:  $
 * $LastChangedRevision:  $
 * $LastChangedDate:  $
 * $HeadURL: $
 *
 * Copyright (c) 2008, Stein Gunnar Bakkeby
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Stein Gunnar Bakkeby nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.googlecode.attention.at;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.googlecode.attention.PhonebookEntry;
import com.googlecode.attention.PhonebookEntryImpl;



public class ReadPhonebookEntries extends AtCommand<ReadPhonebookEntries> {

  private int firstIndex;
  private int lastIndex;
  private int maxNumberLength;
  private int maxTextLength;
  
  private ArrayList<PhonebookEntry> entries;
  
  public ReadPhonebookEntries(AtListener<ReadPhonebookEntries> listener) {
    super(listener);
  }

  @Override
  protected ReadPhonebookEntries getThis() {
    return this;
  }
  
  public void prepareTest() {
    setCommand("AT+CPBR=?", Command.TEST);
  }
  
  /**
   * This method can only be used after a test command has successfully
   * gathered data from the Mobile memory storage.
   */
  public void prepareExecute() {
    if (lastIndex == 0) throw new IllegalStateException(
        "This method can only be used after a test command has successfully "
      + "gathered data from the Mobile memory storage");
    
    prepareExecute(firstIndex, lastIndex);
  }
  
  public void prepareExecute(final int index) {
    setCommand("AT+CPBR=" + index, Command.EXECUTE);
  }
  
  public void prepareExecute(final int index, final int lastIndex) {
    setCommand("AT+CPBR=" + index + "," + lastIndex, Command.EXECUTE);
  }
  
  @Override
  protected void parseTest(final String response) {
    final Pattern pattern = Pattern.compile(
        "\\+CPBR: [(]([0-9])-([0-9]+)[)],([0-9]+),([0-9]+)");
    final Matcher matcher = pattern.matcher(response);
    if (matcher.find()) {
      final String firstIndex = matcher.group(1);
      final String lastIndex = matcher.group(2);
      final String maxNumberLength = matcher.group(3);
      final String maxTextLength = matcher.group(4);
      this.firstIndex = Integer.parseInt(firstIndex);
      this.lastIndex = Integer.parseInt(lastIndex);
      this.maxNumberLength = Integer.parseInt(maxNumberLength);
      this.maxTextLength = Integer.parseInt(maxTextLength);
    }
  }
  
  @Override
  protected void parseExecute(final String response) {
    if (entries == null) {
      entries = new ArrayList<PhonebookEntry>();
    }
    final Pattern pattern = Pattern.compile(
        "\\+CPBR: ([0-9]+),\"([+0-9A-Za-z]+)\",([0-9]+),\"([^\"]+)\"");
    final Matcher matcher = pattern.matcher(response);
    while (matcher.find()) {
      final int memoryIndex = Integer.parseInt(matcher.group(1));
      String number = matcher.group(2);
      if (number != null && number.length() > 1) {
        if (number.charAt(number.length() - 1) < 20) {
          number = number.substring(0, number.length() - 2);
        }
      }
      final int toa = Integer.parseInt(matcher.group(3));
      final String name = matcher.group(4);
      entries.add(new PhonebookEntryImpl(memoryIndex, number, toa, name));
    }
  }
  
  public int getFirstIndex() {
    return firstIndex;
  }
  
  public int getLastIndex() {
    return lastIndex;
  }
  
  public int getMaxNumberLength() {
    return maxNumberLength;
  }
  
  public int getMaxTextLength() {
    return maxTextLength;
  }
  
  public PhonebookEntry[] getPhonebookEntries() {
    if (entries == null) {
      return new PhonebookEntry[0];
    }
    return entries.toArray(new PhonebookEntry[entries.size()]);
  }
  
  public Command getTypeOfCommand() {
    return type;
  }

}
